package org.pragma;

import java.util.ArrayList;
import java.util.List;

import org.pragma.objects.PragmaList;
import org.pragma.objects.PragmaObject;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PragmaBlock extends PragmaObject {

	List<PragmaParameter> parameters = new ArrayList<PragmaParameter>();
	//PragmaBlock block = new PragmaBlock();
	PragmaList<PragmaCall> calls = new PragmaList<PragmaCall>();
	String name;
	
	public PragmaBlock() {
		
	}
	
	public PragmaBlock(String string) {
		name = string;
	}

	public List<PragmaParameter> getParameters() {
		return parameters;
	}

	
	public PragmaObject execute( PragmaContext ctx, List<PragmaObject> parameters) throws Exception {
		PragmaContext localContext = new PragmaContext();
		localContext.setCtxTitle(name);
		localContext.setParent(ctx);
		Integer i = new Integer(0);
		for(PragmaParameter pmp : this.parameters){
			localContext.set(pmp.getName(),parameters.get(i));
		}
		PragmaObject result =null;
		for(PragmaCall call:calls){
			result = call.execute(localContext);
		}
		return result;
	}
	
	public PragmaBlock add(PragmaCall statement) {
		calls.add(statement);
		return this;
	}

	public PragmaBlock addParameter(PragmaParameter pragmaMethodParameter) {
		parameters.add(pragmaMethodParameter);
		return this;
	}

	
	public String getName() {
		return name;
	}
	
	public String toString(){
		return name+"()";
	}

	@Override
	public String display(String margin) {
		String result =  margin+"Method "+name+"\n";
		if(!parameters.isEmpty()){
			result+= margin+displayIndent+"Parameters"+"\n";
			for(PragmaParameter parameter : parameters){
				result+= parameter.display(margin+displayIndent+displayIndent)+"\n";
			}
		}
		result += margin+displayIndent+"Block\n";
		for (PragmaCall call : calls){
			//System.out.println("executing : "+call.toString());
			result += call.display(margin+displayIndent+displayIndent)+"\n";
			
		}
		return result;
	}

	public PragmaBlock load(Element elem) {
		if(elem.getAttribute("name")!=null){
			name = elem.getAttribute("name");
		}
		NodeList nl = elem.getChildNodes();
		for(Integer i=0,n=nl.getLength();i<n;i++){
			Node node = nl.item(i);
			if(node.getNodeType()==Node.ELEMENT_NODE){
				if(node.getNodeName().equalsIgnoreCase("call")){
					calls.add(new PragmaCall().load((Element)node));
				}
			}
		}
		return this;
	}

	
}
